﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Newtonsoft.Json.Linq;

namespace 批量注册
{
    public partial class dns : Office2007Form
    {
        public dns()
        {
            InitializeComponent();
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.Columns[0].FillWeight = 15;
            dataGridView1.Columns[1].FillWeight = 30;
            dataGridView1.Columns[2].FillWeight = 55;

            buttonX2.Enabled = false;
            buttonX3.Enabled = false;
            buttonX4.Enabled = false;
            buttonX5.Enabled = false;
            checkBox1.Checked = true;
            checkBox2.Checked = true;
            checkBox3.Checked = true;
            radioButton1.Checked = true;
            txtMX.Text = "5";
            AddToRichtextbox("网站限制，解析操作延时较长\r\n");
            AddToRichtextbox("请先登录\r\n");
        }

        private CookieContainer cco; //存储登陆后需要的cookie

        private bool login(out CookieContainer cco2)
        {


            ////进行登录
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;

            httpWebRequest = (HttpWebRequest) HttpWebRequest.Create("https://www.dns.com/member/login");
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
            httpWebRequest.Method = "Post";
            httpWebRequest.Referer = "https://www.dns.com";
            httpWebRequest.UserAgent =
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";

            //添加post数据
            string postData = "email=" + txtUserName.Text.Trim() + "&password=" + txtPassword.Text.Trim();
            byte[] byteRequest = Encoding.Default.GetBytes(postData);
            httpWebRequest.ContentLength = byteRequest.Length;
            Stream stream;
            stream = httpWebRequest.GetRequestStream();
            stream.Write(byteRequest, 0, byteRequest.Length);
            stream.Close();

            webResponse = (HttpWebResponse) httpWebRequest.GetResponse();
            string posthtml = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            cco2 = new CookieContainer();
            cco2.SetCookies(new Uri("https://www.dns.com"), webResponse.Headers.Get("Set-Cookie"));

            JObject jo = JObject.Parse(posthtml);

            if (jo["code"].ToString() == "successful")
            {
                txtUserName.Enabled = false;
                txtPassword.Enabled = false;

                return true;
            }
            else
            {
                cco2 = null;
                return false;
            }
        }

        /// <summary>
        /// 将域名和对应IP的www和@解析IP绑定
        /// 此函数对应于批量添加页面提交的数据
        /// </summary>
        /// <param name="coc"></param>
        /// <param name="xsrf"></param>
        /// <param name="domainName"></param>
        /// <param name="IP"></param>
        /// <returns></returns>
        private bool DomainAdd(CookieContainer coc, string domainName, out string domainId)
        {
            string postdata = "domains=" + domainName;
            //  string cookietmp;
            string strResponse = PostHtmlString("https://www.dns.com/member/addDomain?controller=operate/checkDomain",
                "https://www.dns.com/member/addDomain", coc, postdata);
            JObject jo = JObject.Parse(strResponse);

            if ((string) jo["code"] == "successful")
            {
                domainId = (string) jo["data"]["okDomain"][0]["domainID"];
                return true;
            }
            else
            {
                domainId = "0";
                return false;
            }
        }

        private bool DomainToIpType(CookieContainer coc, string IP, string id, int type)
        {
            string postdata;
            switch (type)
            {
                case 1:
                    postdata = "action=addRecord&recordName=www&type=A&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    break;
                case 2:
                    postdata = "action=addRecord&recordName=@&type=A&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    ;
                    break;
                case 3:
                    postdata = "action=addRecord&recordName=*&type=A&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    ;
                    break;
                case 4:
                    postdata = "action=addRecord&recordName=www&type=CNAME&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    break;
                case 5:
                    postdata = "action=addRecord&recordName=@&type=CNAME&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    ;
                    break;
                case 6:
                    postdata = "action=addRecord&recordName=*&type=CNAME&viewID=0&recordValue=" + IP +
                               "&TTL=600&domainID=" + id;
                    ;
                    break;
                case 7:
                    postdata = "action=addRecord&recordName=www&type=MX&viewID=0&recordValue=" + IP +
                               "&MX=" + txtMX.Text.Trim() + "&TTL=600&domainID=" + id;
                    break;
                case 8:
                    postdata = "action=addRecord&recordName=@&type=MX&viewID=0&recordValue=" + IP +
                               "&MX=" + txtMX.Text.Trim() + "&TTL=600&domainID=" + id;
                    ;
                    break;
                case 9:
                    postdata = "action=addRecord&recordName=*&type=MX&viewID=0&recordValue=" + IP +
                               "&MX=" + txtMX.Text.Trim() + "&TTL=600&domainID=" + id;
                    ;
                    break;
                default:
                    MessageBox.Show("error in DomainToIpType");
                    return false;
            }

            //  string cookietmp;
            string strResponse =
                PostHtmlString("https://www.dns.com/member/domain/detail/" + id + "?controller=members/operate",
                    "https://www.dns.com/member/domain/detail/" + id, coc, postdata);
            JObject jo = JObject.Parse(strResponse);

            if ((string) jo["code"] == "successful")
            {
                return true;
            }
            else
            {
                MessageBox.Show((string) jo["message"]);
                return false;
            }
        }

        private bool DeleteDomain(CookieContainer coc, string domainId)
        {
            string postdata = "domainsID=" + domainId + "&action=delete";
            //   string cookietmp;
            string strResponse = PostHtmlString("https://www.dns.com/?controller=members/operate",
                "https://www.dns.com/member/domain", coc, postdata);
            JObject jo = JObject.Parse(strResponse);

            if ((string) jo["code"] == "successful")
            {
                return true;
            }
            else
            {
                MessageBox.Show((string) jo["message"]);
                return false;
            }
        }

        /// <summary>
        /// 得到登陆账户下已添加的域名
        /// </summary>

        /// <returns></returns>
        private DataTable GetDomainList()
        {

            string html = GetHtmlString("https://www.dns.com/member/domain-1-100", "https://www.dns.com/member/login", cco);

            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("domain");
            StringReader tmpSR = new StringReader(html);
            while (true)
            {
                string strtmp = tmpSR.ReadLine();
                if (null != strtmp)
                {
                    if (strtmp.Contains("member/domain/detail/"))
                    {
                        DataRow dr = dt.NewRow();
                        strtmp = strtmp.Substring(strtmp.IndexOf(@"detail/"));
                        dr["id"] = strtmp.Substring(7, strtmp.IndexOf(@">") - 8);
                        strtmp = strtmp.Substring(strtmp.IndexOf(@">"));
                        dr["domain"] = strtmp.Substring(1, strtmp.IndexOf(@"<") - 1);
                        dt.Rows.Add(dr);
                    }
                }
                else
                {
                    break;
                }
            }


            return dt;
        }

        /// <summary>
        /// get方法请求 根据URL获得返回的页面字符串与cookie
        /// </summary>
        /// <param name="URL">访问的页面地址</param>
        /// <param name="cookie">返回的cookie</param>
        /// <returns>返回页面的字符串数据</returns>
        private string GetHtmlString(string URL, out string cookie)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;

            httpWebRequest = (HttpWebRequest) HttpWebRequest.Create(URL);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
            httpWebRequest.Method = "Get";

            httpWebRequest.UserAgent =
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            webResponse = (HttpWebResponse) httpWebRequest.GetResponse();
            string strhtml = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            cookie = webResponse.Headers.Get("Set-Cookie");
            return strhtml;
        }

        /// <summary>
        /// 得到get请求返回的页面字符串和cookie
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="referUrl"></param>
        /// <param name="coc"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        private string GetHtmlString(string URL, string referUrl, CookieContainer coc)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;

            httpWebRequest = (HttpWebRequest) HttpWebRequest.Create(URL);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
            httpWebRequest.Method = "Get";
            httpWebRequest.Referer = referUrl;
            httpWebRequest.UserAgent =
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.CookieContainer = cco;
            webResponse = (HttpWebResponse) httpWebRequest.GetResponse();
            string strhtml = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();

            return strhtml;
        }

        /// <summary>
        /// 不带输出cookie的post方法
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="referUrl"></param>
        /// <param name="coc"></param>
        /// <param name="postdata"></param>
        /// <returns></returns>
        private string PostHtmlString(string URL, string referUrl, CookieContainer coc, string postdata)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;

            httpWebRequest = (HttpWebRequest) HttpWebRequest.Create(URL);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
            httpWebRequest.Method = "Post";
            httpWebRequest.Referer = referUrl;
            httpWebRequest.UserAgent =
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.CookieContainer = coc;
            byte[] byteRequest = Encoding.Default.GetBytes(postdata);
            //添加post数据
            httpWebRequest.ContentLength = byteRequest.Length;
            Stream stream;
            stream = httpWebRequest.GetRequestStream();
            stream.Write(byteRequest, 0, byteRequest.Length);
            stream.Close();

            webResponse = (HttpWebResponse) httpWebRequest.GetResponse();
            string strhtml = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            // cookie = webResponse.Headers.Get("Set-Cookie");
            return strhtml;
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == "" || txtPassword.Text == "")
            {
                MessageBox.Show("请输入用户名或密码");
                return;
            }
            try
            {
                if (login(out cco))
                {
                    buttonX1.Enabled = false;
                    buttonX2.Enabled = true;
                    buttonX3.Enabled = true;
                    buttonX4.Enabled = true;
                    buttonX5.Enabled = true;
                    txtUserName.Enabled = false;
                    txtPassword.Enabled = false;
                    AddToRichtextbox("登陆成功！\r\n");
                }
                else
                {
                    MessageBox.Show("登陆失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }



        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            //string xsrf;
            //CookieContainer cco;
            //login(out cco, out xsrf);
            try
            {
                DataTable tmpdt = GetDomainList();
                dataGridView1.AutoGenerateColumns = false; //这句话非常重要
                dataGridView1.DataSource = tmpdt;
                dataGridView1.Columns[1].DataPropertyName = tmpdt.Columns[0].ToString();
                dataGridView1.Columns[2].DataPropertyName = tmpdt.Columns[1].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }

        }

        private void buttonX4_Click(object sender, EventArgs e)
        {
            if (dataGridView2.Rows.Count != dataGridView3.Rows.Count)
            {
                MessageBox.Show("域名与IP数目不一致，请检查");
                return;
            }
            Thread tr = new Thread(new ThreadStart(bangding));
            tr.Start();
        }

        private void bangding()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("域名");
            dt.Columns.Add("ip");
            dataGridView2.EndEdit();
            dataGridView3.EndEdit();
            try
            {
                int inum = dataGridView2.Rows.Count;//因为datagridview中的行数随时在改变，如果用循环将导致循环的不准确
                for (int i = 0; i < inum - 1; i++)
                {
                    string domainName = dataGridView2.Rows[0].Cells[0].Value.ToString();
                    string ip = dataGridView3.Rows[0].Cells[0].Value.ToString();
                    string domainId;
                    if (DomainAdd(cco, domainName, out domainId))
                    {
                        AddToRichtextbox(domainName + " 添加成功\r\n");
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        MessageBox.Show("添加记录失败！");
                        return;
                    }
                    if (checkBox1.Checked == true && radioButton1.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 1))
                        {
                            AddToRichtextbox(domainName + " 添加www记录成功，类型A IP：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加www记录失败！");
                            return;
                        }
                    }
                    if (checkBox2.Checked == true && radioButton1.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 2))
                        {
                            AddToRichtextbox(domainName + " 添加@记录成功，类型A IP：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加@记录失败！");
                            return;
                        }
                    }
                    if (checkBox3.Checked == true && radioButton1.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 3))
                        {
                            AddToRichtextbox(domainName + " 添加*记录成功，类型A IP：" + ip + "\r\n");
                           Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加*记录失败！");
                            return;
                        }
                    }
                    if (checkBox1.Checked == true && radioButton2.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 4))
                        {
                            AddToRichtextbox(domainName + " 添加www记录成功，类型CNAME 记录值：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加www记录失败！");
                            return;
                        }
                    }
                    if (checkBox2.Checked == true && radioButton2.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 5))
                        {
                            AddToRichtextbox(domainName + " 添加@记录成功，类型CNAME 记录值：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加@记录失败！");
                            return;
                        }
                    }
                    if (checkBox3.Checked == true && radioButton2.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 6))
                        {
                            AddToRichtextbox(domainName + " 添加*记录成功，类型CNAME 记录值：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加*记录失败！");
                            return;
                        }
                    }
                    if (checkBox1.Checked == true && radioButton3.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 7))
                        {
                            AddToRichtextbox(domainName + " 添加www记录成功，类型MX 记录值：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加www记录失败！");
                            return;
                        }
                    }
                    if (checkBox2.Checked == true && radioButton3.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 8))
                        {
                            AddToRichtextbox(domainName + " 添加@记录成功，类型MX 记录值：" + ip + "\r\n");
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            MessageBox.Show("添加@记录失败！");
                            return;
                        }
                    }
                    if (checkBox3.Checked == true && radioButton3.Checked == true)
                    {
                        if (DomainToIpType(cco, ip, domainId, 9))
                        {
                            AddToRichtextbox(domainName + " 添加*记录成功，类型MX 记录值：" + ip + "\r\n");
                            Thread.Sleep(2500);
                        }
                        else
                        {
                            MessageBox.Show("添加*记录失败！");
                            return;
                        }
                    }
                    deleteRowFromDatagridview();
                    Thread.Sleep(200);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            MessageBox.Show("已完成操作");

        }
        public delegate void DelegatedeleteRowFromDatagridview();

        private void deleteRowFromDatagridview()
        {
            if (this.InvokeRequired)
            {
                DelegatedeleteRowFromDatagridview d = new DelegatedeleteRowFromDatagridview(deleteRowFromDatagridview);
                this.BeginInvoke(d);
            }
            else
            {
                dataGridView2.Rows.RemoveAt(0);
                dataGridView3.Rows.RemoveAt(0);
                dataGridView2.Update();
                dataGridView3.Update();
            }
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            txtUserName.Enabled = true;
            txtPassword.Enabled = true;
            buttonX1.Enabled = true;
            buttonX2.Enabled = false;
            buttonX3.Enabled = false;
            buttonX4.Enabled = false;
            buttonX5.Enabled = false;
        }

        private void buttonX5_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("是否删除所选择的域名？", "确认", MessageBoxButtons.YesNo))
            {
                string deleteDomainID = "";
                string deleteDomainName = "";
                try
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        if ((bool) dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                        {
                            deleteDomainID += dataGridView1.Rows[i].Cells[1].Value.ToString() + "_";
                            deleteDomainName += dataGridView1.Rows[i].Cells[2].Value.ToString() + "\r\n";
                        }
                    }
                    if (DeleteDomain(cco, deleteDomainID))
                    {
                        AddToRichtextbox("已删除域名 " + deleteDomainName);
                    }
                    else
                    {
                        MessageBox.Show("删除失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw;
                }

            }
        }

        private void buttonX6_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
        }

        private void buttonX7_Click(object sender, EventArgs e)
        {
            dataGridView2.Rows.Clear();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {
                if ((bool) dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue == false)
                {
                    dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
                }
                else
                {
                    dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
                }
            }
        }

        public delegate void DelegateAddToRichtextbox(string str); //委托相当于一个描述函数的地址

        private void AddToRichtextbox(string str)
        {
            if (this.InvokeRequired)
            {
                DelegateAddToRichtextbox a = new DelegateAddToRichtextbox(AddToRichtextbox);
                this.BeginInvoke(a, str); //这里调用的委托,其是在主线程内的,其声明实在主函数中声明的,
            }
            else
            {
                richTextBox1.AppendText(str);
            }
            //  Thread.Sleep(10);
        }

        private void buttonX9_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if ((bool) dataGridView1.Rows[i].Cells[0].EditedFormattedValue == false)
                {
                    dataGridView1.Rows[i].Cells[0].Value = true;
                }
            }
        }

        private void buttonX10_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if ((bool) dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                {
                    dataGridView1.Rows[i].Cells[0].Value = false;
                }
                else
                {
                    dataGridView1.Rows[i].Cells[0].Value = true;
                }
            }
        }

        private void dns_FormClosing(object sender, FormClosingEventArgs e)
        {
        //    this.Hide();
        //    e.Cancel = true;
        }

        private void dataGridView2_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            labelX3.Text = "共 " + (dataGridView2.RowCount - 1).ToString() + " 条";
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView3_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            labelX4.Text = "共 " + (dataGridView3.RowCount - 1).ToString() + " 条";
        }

        private void dataGridView2_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            labelX3.Text = "共 " + (dataGridView2.RowCount - 1).ToString() + " 条";
        }

        private void dataGridView3_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            labelX4.Text = "共 " + (dataGridView3.RowCount - 1).ToString() + " 条";
        }

        private void buttonX8_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader m_streamReader = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.Default);
                string s;
                while ((s = m_streamReader.ReadLine()) != null)
                {
                    int index = dataGridView2.Rows.Add();
                    dataGridView2.Rows[index].Cells[0].Value = s;
                }
            }
        }

        private void buttonX11_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader m_streamReader = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.Default);
                string s;
                while ((s = m_streamReader.ReadLine()) != null)
                {
                    int index = dataGridView3.Rows.Add();
                    dataGridView3.Rows[index].Cells[0].Value = s;
                }
            }
        }

        private void buttonX12_Click(object sender, EventArgs e)
        {
            dataGridView3.Rows.Clear();
        }

        private void buttonX13_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //实例化一个保存对话框
            sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "";
            sf.FileName = "所选域名";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") //如果没有输入文件名
                {
                    return;
                }
                try
                {
                    StreamWriter sw = null; //定义一个文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.Unicode);
                   // sw.WriteLine("字段1\t\t字段2\t\t字段3\t\t字段4"); //写入表中的标题
                    for (int i = 0; i < dataGridView1.Rows.Count; i++) //循环写入第一个表里面的数据
                    {
                        if ((bool) dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                        {
                            for (int j = 1; j < dataGridView1.Columns.Count; j++)
                        {                      
                            str = dataGridView1.Rows[i].Cells[j].Value.ToString();
                            sw.Write(str + "\t");                        
                        }                    
                           sw.WriteLine("");
                        }                   
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("数据导出成功！", "提示：");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}
